package com.jy.modules.cims.interact;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.CimsIrtUrlConstant;
import com.jy.modules.cims.data.dto.InteractEnsureDto;
import com.jy.modules.cims.data.dto.LoanDetailDto;
import com.jy.modules.cims.data.dto.credit.PublicSettleParamDto;
import com.jy.modules.cims.data.dto.credit.PublicSettleResultDto;
import com.jy.modules.cims.data.dto.loan.LoanBuybackSettleCreditDto;
import com.jy.modules.cims.data.dto.loan.LoanBuybackSettleDto;
import com.jy.modules.cims.data.dto.loan.LoanDealSettleDto;
import com.jy.modules.cims.data.interact.core.loan.request.LoanTransferDTO;
import com.jy.modules.cims.data.interact.core.loan.request.Request4048DTO;
import com.jy.modules.cims.data.interact.core.loan.request.Request4049DTO;
import com.jy.modules.cims.data.interact.core.loan.request.RequestLoanBuybackSettleCreditDTO;
import com.jy.modules.cims.data.interact.core.loan.request.RequestLoanBuybackSettleDTO;
import com.jy.modules.cims.data.interact.core.loan.response.Response4048DTO;
import com.jy.modules.cims.data.interact.core.loan.response.Response4049DTO;
import com.jy.platform.core.message.ResponseMsg;

/**
 * <b>类名称：</b>CIRLoanSettleIFImpl <br/>
 * <b>类描述：贷款转出业务结算交互实现类</b><br/>
 * <b>创建人：</b>yanjingying<br/>
 * <b>修改人：</b><br/>
 * <b>修改时间：</b>2016-08-19 下午10:00:00<br/>
 * <b>修改备注：</b><br/>
 * <b>版本信息：</b>v1.0.0<br/>
 */
@Service("com.jy.modules.cims.interact.CIRLoanSettleIFImpl")
public class CIRLoanSettleIFImpl {
	private static final Logger logger = LoggerFactory.getLogger(CIRLoanSettleIFImpl.class);
	
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.InteractClient")
	public InteractClient interactClient;
	

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	public IInteractAssist iInteractAssist;
	
    /**
     * 发送贷款回购结算申请
     * @Title sendLoanBuybackSettleApply
     * @Description 回购贷款、赎回债权一起发送进行结算
     * @param publicSettleParamDto 公共结算参数
     * @return PublicSettleResultDto  公共结算结果
     * @throws Exception
     * @author yanjingying
     * @date 2016-8-19 10:00:00
     */
    public PublicSettleResultDto sendLoanBuybackSettleApply(PublicSettleParamDto publicSettleParamDto) throws Exception{
    	logger.info(">>>>>>>>>>贷款回购结算申请4049：获取公共结算参数参数值");	
    	List<LoanBuybackSettleDto> loanBuybackSettleDtoList = publicSettleParamDto.getLoanBuybackSettleDtoList();  //回购贷款列表
    	List<LoanBuybackSettleCreditDto> loanBuybackSettleCreditDtoList = publicSettleParamDto.getLoanBuybackSettleCreditDtoList(); //回购债权列表
    	
    	logger.info(">>>>>>>>>>开始封装贷款回购结算申请req参数");	
    	Request4049DTO req = new Request4049DTO();
    	req.setFrontTransNo(publicSettleParamDto.getFrontTransNo());  //合作机构交易流水号
    	req.setInterfaceNo((String) CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_LOAN_BUYBACK_SETTLE_APPLY_TO_CORE).get(CimsIrtUrlConstant.IRT_CODE));  //接口编码
        req.setBusiCode((String) CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_LOAN_BUYBACK_SETTLE_APPLY_TO_CORE).get(CimsIrtUrlConstant.IRT_BUSICODE)); //业务编码
        req.setApplyId(publicSettleParamDto.getApplyCode());//结算编号
    	req.setApplyName(publicSettleParamDto.getApplyName());//申请人
    	req.setCCode(publicSettleParamDto.getCCode()); //合作机构
        
    	logger.info(">>>>>>>>>>循环遍历回购贷款结算列表List，封装至req参数中");	
    	List<RequestLoanBuybackSettleDTO> requestLoanDtoList = new ArrayList<RequestLoanBuybackSettleDTO>();
    	for(LoanBuybackSettleDto settleDto : loanBuybackSettleDtoList){
    		RequestLoanBuybackSettleDTO requestLoanDto = new RequestLoanBuybackSettleDTO();
    		requestLoanDto.setBatchId(settleDto.getBatchId());    //回购批次号
    		requestLoanDto.setContractNo(settleDto.getContractNo());   //合同编号
    		requestLoanDto.setBuybackContractValue(settleDto.getBuybackContractValue());  //回购贷款金额
    		requestLoanDto.setBuybackCreditValue(settleDto.getBuybackCreditValue()); //回购债权金额
    		requestLoanDto.setServiceCharge(settleDto.getServiceCharge()); //服务费(退费金额)
    		requestLoanDto.setCashDeposit(settleDto.getCashDeposit());     //保证金(退费金额)
    		requestLoanDto.setGuaranteeFee(settleDto.getGuaranteeFee());  //担保费(退费金额)
    		requestLoanDtoList.add(requestLoanDto);
     	}
    	req.setLoanList(requestLoanDtoList);
    	
    	logger.info(">>>>>>>>>>循环遍历回购债权结算列表List，封装至req参数中");
    	List<RequestLoanBuybackSettleCreditDTO> requestCreditDtoList = new ArrayList<RequestLoanBuybackSettleCreditDTO>();
    	for(LoanBuybackSettleCreditDto settleCreditDto : loanBuybackSettleCreditDtoList){
    		RequestLoanBuybackSettleCreditDTO requestCreditDto = new RequestLoanBuybackSettleCreditDTO();
    		requestCreditDto.setBatchId(settleCreditDto.getBatchId());  //赎回批次号
    		requestCreditDto.setTransferId(settleCreditDto.getTransferId());  //债权转让编号
    		requestCreditDtoList.add(requestCreditDto);
    	}
    	req.setCreditList(requestCreditDtoList);
    	logger.info(">>>>>>>>>>封装贷款回购结算申请req参数结束");	
        
    	logger.info(">>>>>>>>>>发送报文给核心系统并获取响应报文");
    	InteractEnsureDto ensureDto = new InteractEnsureDto();
        ensureDto.setDealCode(publicSettleParamDto.getDealCode());//交易流水号
        Response4049DTO responseMsg = interactClient.sendReqToCore(
                (String) CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_LOAN_BUYBACK_SETTLE_APPLY_TO_CORE).get(
                        CimsIrtUrlConstant.IRT_URL), req, new TypeReference<ResponseMsg<Response4049DTO>>() {},
                ensureDto);
        if (responseMsg != null){
        	PublicSettleResultDto rltdto = PublicSettleResultDto.successPublicSettleResultDto();
        	rltdto.setApplyCode(responseMsg.getApplyId());         //结算申请编号
        	rltdto.setFrontTransNo(responseMsg.getFrontTransNo()); //合作机构交易流水号
        	rltdto.setCoreTransNo(responseMsg.getCoreTransNo());  //核心交易流水号
        	rltdto.setBusiCode(responseMsg.getBusiCode());  //业务编码
        	rltdto.setInterfaceNo(responseMsg.getInterfaceNo());  //接口编码
        	rltdto.setRetCode(responseMsg.getRetCode());   //返回码        0000：成功  0001：失败  9999:日终处理中
        	rltdto.setRetTime(responseMsg.getRetTime());   //返回时间
        	rltdto.setRetMsg(responseMsg.getRetMsg());     //返回信息
        	return rltdto;
        }
    	return null;
    }
    /**
     * 
     * @Title sendLoanDealSettleApply
     * @Description TODO
     * @param publicSettleParamDto
     * @return
     * @throws Exception 
     * PublicSettleResultDto 
     * @author lizhiqiang
     * @date 2016-8-24-下午2:18:34
     * @update 
     * @throws
     */
    public PublicSettleResultDto sendLoanDealSettleApply(LoanDealSettleDto loanDealSettleDto) throws Exception{
    	List<LoanDetailDto> loanList = loanDealSettleDto.getLoanList();
    	
    	Request4048DTO req = new Request4048DTO();
    	req.setFrontTransNo(iInteractAssist.getBusiNoForInteract());  //合作机构交易流水号
    	req.setInterfaceNo((String) CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_LOAN_SETTLE_APPLY_TO_CORE).get(CimsIrtUrlConstant.IRT_CODE));  //接口编码
        req.setBusiCode((String) CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_LOAN_SETTLE_APPLY_TO_CORE).get(CimsIrtUrlConstant.IRT_BUSICODE)); //业务编码
        
    	req.setApplyName(loanDealSettleDto.getApplyName());//申请人
    	req.setcCode(loanDealSettleDto.getCooperorgCode()); //合作机构
    	req.setCount(loanDealSettleDto.getCount());//明细数量
    	req.setTotalServiceCharge(loanDealSettleDto.getTotalServiceCharge());//服务费
    	req.setTotalCashDeposit(loanDealSettleDto.getTotalCashDeposit());//保证金
        req.setAccountFeesFlag(loanDealSettleDto.getAccountFeesFlag());
        req.setApplyId(loanDealSettleDto.getApplyId());//结算编号
    	List<LoanTransferDTO> transferList = new ArrayList<LoanTransferDTO>();
    	for(LoanDetailDto loanDetail : loanList){
//    		if(StringUtils.isEmpty(req.getApplyId()))
//    		req.setApplyId(loanDetail.getSettleApplyId());//结算编号
    		
    		LoanTransferDTO loanTransferDTO = new LoanTransferDTO();
    		/** 结算编号 */
    		loanTransferDTO.setAppId(loanDealSettleDto.getApplyId());
    		/** 合同编号 */
    		loanTransferDTO.setContractNo(loanDetail.getContractNo());
    		/** 服务费 */
    		loanTransferDTO.setServiceCharge(loanDetail.getServiceCharge());
    		/** 保证金 */
    		loanTransferDTO.setCashDeposit(loanDetail.getCautionMoney());
    		/** 每期还款金额 */
    		loanTransferDTO.setEachRepaymentValue(loanDetail.getPaybackAmount());
    		/** 合同金额 */
    		loanTransferDTO.setContractValue(loanDetail.getContractAmount());
    		/** 放款金额 */
    		loanTransferDTO.setLoanValue(loanDetail.getLoanAmount());
    		/** 出借人保证基金 */
    		loanTransferDTO.setCreditorDeposit(loanDetail.getCreditorDeposit());
    		/** 信用保证金 */
    		loanTransferDTO.setCreditBail(loanDetail.getCreditBail());
    		/**借款人编号*/
    		loanTransferDTO.setLoanUserid(loanDetail.getCustCode());
    		/**贷款产品代码*/
    		loanTransferDTO.setLoanProductCode(loanDetail.getProductCode());
    		/**贷款产品名称*/
    		loanTransferDTO.setLoanProductName(loanDetail.getProductName());
    		/**贷款用途*/
    		loanTransferDTO.setLoanUse(loanDetail.getLoanPurpose());
    		/**还款方式*/
    		loanTransferDTO.setRepaymentType(loanDetail.getRepayType());
    		/** 合同类型 */
    		loanTransferDTO.setLoanType(CimsConstant.mapProductType.get(loanDetail.getProductType()));
    		/** 贷款到期日 */
    		loanTransferDTO.setDueDate(loanDetail.getEndDate());
    		/** 账单日 */
    		loanTransferDTO.setBillDate(Integer.valueOf(loanDetail.getRepayDay()));
    		/** 放款日期 */
    		loanTransferDTO.setInitialDate(loanDetail.getFundDate());
    		/** 贷款月利率 */
    		loanTransferDTO.setLoanMonthlyInterest(loanDetail.getMonthRate());
    		/** 还款期数 */
    		loanTransferDTO.setRepaymentMonth(Integer.valueOf(loanDetail.getLoanPeriod()));
    		/** 起始还款日期 */
    		loanTransferDTO.setStartRepaymentDate(loanDetail.getFirstPaybackDate());
    		
    		transferList.add(loanTransferDTO);
     	}
    	
    	req.setTransferList(transferList);
        
    	InteractEnsureDto ensureDto = new InteractEnsureDto();
        ensureDto.setDealCode(loanDealSettleDto.getApplyId());//交易流水号
        logger.info("发送贷款转出结算申请>>>>>>>>>>>>>>>>>>>>start");
        Response4048DTO responseMsg = interactClient.sendReqToCore(
                (String) CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_LOAN_SETTLE_APPLY_TO_CORE).get(
                        CimsIrtUrlConstant.IRT_URL), req, new TypeReference<ResponseMsg<Response4048DTO>>() {},
                ensureDto);
        logger.info("发送贷款转出结算申请>>>>>>>>>>>>>>>>>>>>end");
        if (responseMsg != null){
        	PublicSettleResultDto rltdto = PublicSettleResultDto.successPublicSettleResultDto();
        	rltdto.setApplyCode(responseMsg.getApplyId());         //结算申请编号
        	rltdto.setFrontTransNo(responseMsg.getFrontTransNo()); //合作机构交易流水号
        	rltdto.setCoreTransNo(responseMsg.getCoreTransNo());  //核心交易流水号
        	rltdto.setBusiCode(responseMsg.getBusiCode());  //业务编码
        	rltdto.setInterfaceNo(responseMsg.getInterfaceNo());  //接口编码
        	rltdto.setRetCode(responseMsg.getRetCode());   //返回码        0000：成功  0001：失败  9999:日终处理中
        	rltdto.setRetTime(responseMsg.getRetTime());   //返回时间
        	rltdto.setRetMsg(responseMsg.getRetMsg());     //返回信息
        	return rltdto;
        }
    	return null;
    }
}
